<?php
/**
 * Created by PhpStorm.
 * User: J.H
 * Date: 2017/4/8
 * Time: 0:28
 */

namespace lib\helper;


class RunTime
{
    private static $start = null;
    private static $end = null;

    static function start()
    {
        self::$end = null;
        return self::$start = microtime(true);
    }

    static function end()
    {
        return self::$end = microtime(true);
    }

    static function getRunTime($unit = 's', $showUnit = true)
    {
        if (null === self::$start) {
            new \Exception('please call the first start function');
        }
        if (null === self::$end) {
            self::end();
        }
        $duration = round((self::$end - self::$start) * pow(10, self::getPrecision($unit) * 3), 3);

        if ($showUnit) {
            return $duration . " {$unit}";
        } else {
            return $duration;
        }

    }

    private static function getPrecision($unit)
    {
        if (strcasecmp($unit, 's') == 0) {
            return 0;
        }
        return 1;
    }
}